const express = require("express");
const fs = require("fs");
const https = require("https");
const http = require("http");
const path = require("path");
const app = express();

const port = process.env.PORT || 5000;

// // const privateKey = fs.readFileSync("../Nginx_SSL/2_hongbin.xyz.key", "utf8");
// // const certificate = fs.readFileSync(
// //     "../Nginx_SSL/1_hongbin.xyz_bundle.crt",
// //     "utf8"
// // );
// // const credentials = { key: privateKey, cert: certificate };

// const server = https.createServer(credentials, app);
const httpServer = http.createServer(app);

if (process.env.NODE_ENV === "development") {
    if (process.env.HTTP === 'http')
        httpServer.listen(port, () => { console.log("> dev mode on http " + port) });
    else server.listen(port, () => { console.log("> dev mode on https " + port) });
} else {
    if (process.env.HTTP === 'http')
        httpServer.listen(port, () => { console.log("> prev mode on http " + port) });
    else server.listen(port, () => { console.log("> prev mode on https " + port) });
}

app.all("*", function (req, res, next) {
    //设置允许跨域的域名，*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin", "*");
    //允许的header类型
    // res.header("Access-Control-Allow-Headers", ["content-type", "Authorization"]);
    res.header("Access-Control-Allow-Headers", "content-type,Authorization");
    //跨域允许的请求方式
    res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == "options") res.status(200).send();
    //让options尝试请求快速结束
    else next();
});

app.post('*', (req, res, next) => {
    let payload = '';
    req.on('data', (chunk) => payload += chunk);
    req.on("end", () => {
        req.payload = JSON.parse(payload);
        next();
    })
})

const mongo = require('./src/mongo.js');

for (const [key, [method, callback]] of Object.entries(mongo)) {
    app[method](`/${key}`, callback());
}

app.use("/", (req, res, next) => {
    let pathName = req.url;
    console.log(pathName);
    // 提供一个 icon就不会发起/favicon.ico的请求了
    if (pathName == "/") {
        pathName = "/index.html";
    }

    const extName = path.extname(pathName);
    fs.readFile(`../web-db/build${pathName}`, function (err, data) {
        if (err) {
            console.error(err);
            res.status(400).json(err);
        } else {
            const ext = getExt(extName);
            res.writeHead(200, { "Content-Type": ext + "; charset=utf-8" });
            res.write(data);
        }
        res.end();
    });
});

getExt = extName => {
    switch (extName) {
        case ".html":
            return "text/html";
        case ".css":
            return "text/css";
        case ".js":
            return "text/js";
        case ".ico":
            return "image/x-icon";
        case ".png":
            return "image/png";
        default:
            return "text/html";
    }
};